<template>
  <Card>
    <Row>
      <Col :span="12" style="padding-left: 1rem;">
        <v-form :options="options" v-model="form">
          <FormItem>
            <Button @click="start" type="primary">开始</Button>
            <Button @click="stop" type="error">停止</Button>
          </FormItem>
        </v-form>
      </Col>
    </Row>
    <List  border item-layout="vertical">
      <ListItem v-for="(file, i) in form.files" >{{file}}
        <Progress :percent="percent" :stroke-width="20" status="active" text-inside slot="action" v-if="index === i"/>
      </ListItem>
    </List>
  </Card>
</template>

<script>
import ffmpeg from 'fluent-ffmpeg'

/**
 * @作者：陈明明
 * @创建日期 ： 2021/8/4 20:18
 */
export default {
  name: 'mkv2mp4',
  data() {
    return {
      files:[],
      tasks: [],
      form:{
        files:[],
        reduces: ''
      },
      index: -1,
      percent: 0,
      _task:undefined,
      options: [
        {
          type: 'file',
          key: 'files',
          label: '文件',
          multiselectable: true,
          extensions: 'mkv'
        },
        {
          type: 'string',
          key: 'reduces',
          label: '文件名去去重',
        }
      ],
    }
  },
  methods: {
    start() {
      if (this.form.files.length > 0) {
        this.convert(0)
      } else {
        this.$Message.error('尚未选择文件')
      }
    },
    stop() {
      this.tasks = []
      if (this._task) {
        this._task.kill()
      }
    },
    convert(index) {
      let path = this.form.files[index]
      if (!path) {
        this.index = -1
        return
      }
      this.index = index
      let savePath = path
      if (this.form.reduces) {
        let lasI = path.lastIndexOf('\\')
        let fileName = path.substring(lasI + 1, path.length)
        let dir = path.substring(0, lasI + 1)
        let rs = this.form.reduces.split(',')
        rs.forEach(item => {
          fileName = fileName.replace(item, '')
        })
        savePath = dir + fileName
      }

      let cmd = ffmpeg(path)
          .audioBitrate(128)
          .videoCodec('copy')
          .on('progress', (progress) => {
            this.percent = Math.ceil(progress.percent)
            console.log(progress)
          })
          .on('error', (err) => {
            this.index = -1
            this.task = undefined
            console.error(err)
          })
          .on('end', () => {
            this.convert(index + 1)
            this.task = undefined
          })
          .save(savePath.replace('.mkv', '.mp4'))
          this._task = cmd
    }
  }
}
</script>

<style scoped>

</style>